<template>
	<div>
		<van-sticky>
			<div class="searchBox">
				<van-icon name="arrow-left" size="26" @click="goback" />
				<div class="title">{{ title }}</div>
			</div>
		</van-sticky>
		<div style="margin-top: 30px;">
			<van-form @submit="onSubmit" input-align="right" error-message-align="right" show-error>
				<van-cell-group inset>
					<van-field v-model="form.storename" name="店铺名称" label="店铺名称" placeholder="请输入店铺名称" required
						:rules="[{ required: true, message: '请输入店铺名称',trigger:'onChange'}]"
						@update:model-value="storenameInput" />

					<van-field v-model="form.storeType" name="店铺类型" label="店铺类型" placeholder="请输入店铺类型" required is-link
						readonly :rules="[{ required: true, message: '请选择店铺类型',trigger:'onChange'}]"
						@click="storeTypeShowkai" />

					<van-field v-model="form.address" is-link readonly name="area" label="地区选择" placeholder="请选择省市区"
						required @click="showAreakai"
						:rules="[{ required: true, message: '请选择省市区',trigger:'onChange'}]" />

					<van-field v-model="form.detailedAddress" name="详细地址" label="详细地址" placeholder="请输入详细地址" required
						:rules="[{ required: true, message: '请输入详细地址',trigger:'onChange'}]"
						@update:model-value="detailedAddressInput" />

					<van-field name="switch" label="设为默认地址">
						<template #input>
							<van-switch v-model="form.defaultFlag" :active-value="0" :inactive-value="1"
								@change="switchChange" />
						</template>
					</van-field>

					<div style="margin: 16px;">
						<van-button round block type="primary" native-type="submit">
							保存
						</van-button>
					</div>
				</van-cell-group>
			</van-form>

		</div>
		<!-- 编辑地址 -->
		<van-popup v-model:show="showArea" position="bottom" round safe-area-inset-bottom>
			<van-area :model-value="pickerValue" :area-list="areaList" @confirm="onConfirm"
				@cancel="showArea = false" />
		</van-popup>
		<!-- 店铺类型 -->
		<van-popup v-model:show="storeTypeShow" round position="bottom" safe-area-inset-bottom>
			<van-picker :columns="columns" @cancel="storeTypeShow = false" @confirm="storeTypeConfirm"
				:loading="typeloading" />
		</van-popup>
	</div>
</template>

<script setup>
	import {
		useRoute
	} from 'vue-router';
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		showToast
	} from 'vant';
	import {
		areaList
	} from '@vant/area-data';
	import {
		getUserid,
		getIdentity
	} from '@/utils/auth';
	import {
		updateStore,
		addStore
	} from '@/api/deviceStores';


	onMounted(() => {
		getdata();
	});

	const showArea = ref(false);
	const storeTypeShow = ref(false);
	const typeloading = ref(false);
	const title = ref('');
	const tishi = ref('');
	// const router = useRouter();
	const route = useRoute();
	const pickerValue = ref('');
	const updateParams = ref({
		userId: getUserid(),
		storeName: '',
		storeType: '',
		province: '',
		city: '',
		district: '',
		detailedAddress: '',
		defaultFlag: '',
		id: ''
	}); //修改地址参数
	const columns = ref([{
		text: '电影院',
		value: '电影院'
	}, {
		text: '商场',
		value: '商场'
	}, {
		text: '小卖部',
		value: '小卖部'
	}, ]);
	const form = ref({
		storename: '',
		address: '',
		detailedAddress: '',
		storeType: '',
		defaultFlag: undefined
	});
	const addParams = ref({
		userId: getUserid(),
		storeName: '',
		storeType: '',
		province: '',
		city: '',
		district: '',
		detailedAddress: '',
		defaultFlag: '',
	}); //增加地址参数
	// add是新增地址,其他是编辑
	const getdata = () => {
		if (route.params.id == 'add') {
			title.value = '添加地址';
			tishi.value = '添加';
		} else {
			title.value = '编辑地址';
			tishi.value = '编辑';
			const update = JSON.parse(route.params.data);
			updateParams.value.storeName = update.storeName;
			updateParams.value.storeType = update.storeType;
			updateParams.value.province = update.province;
			updateParams.value.city = update.city;
			updateParams.value.district = update.district;
			updateParams.value.detailedAddress = update.detailedAddress;
			updateParams.value.defaultFlag = update.defaultFlag;
			updateParams.value.id = update.id;
			form.value.storename = update.storeName;
			form.value.address = `${update.province + '-' + update.city + '-' + update.district}`;
			form.value.detailedAddress = update.detailedAddress;
			form.value.defaultFlag = update.defaultFlag;
			form.value.storeType = update.storeType;
		}
	};
	//店铺名称
	const storenameInput = (name) => {
		updateParams.value.storeName = name;
		addParams.value.storeName = name;
	};
	//店铺类型
	const storeTypeShowkai = () => {
		typeloading.value = true;
		storeTypeShow.value = true;
		// 模拟接口
		setTimeout(() => {
			typeloading.value = false;
		}, 200)
	};
	const storeTypeConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		form.value.storeType = selectedOptions[0].text;
		updateParams.value.storeType = selectedOptions[0].value;
		addParams.value.storeType = selectedOptions[0].value;
		storeTypeShow.value = false;
	};
	//详细地址
	const detailedAddressInput = (address) => {
		updateParams.value.detailedAddress = address;
		addParams.value.detailedAddress = address;
	};
	// 默认地址
	const switchChange = ({
		values
	}) => {
		updateParams.value.defaultFlag = form.value.defaultFlag;
		addParams.value.defaultFlag = form.value.defaultFlag;
	};
	// 选择省市区
	const showAreakai = () => {
		showArea.value = true;
	};
	const onConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		pickerValue.value = selectedValues.length ? selectedValues[selectedValues.length - 1] : '';
		showArea.value = false;
		form.value.address = selectedOptions.map((item) => item.text).join('-');
		updateParams.value.province = selectedOptions[0].text;
		updateParams.value.city = selectedOptions[1].text;
		updateParams.value.district = selectedOptions[2].text;
		addParams.value.province = selectedOptions[0].text;
		addParams.value.city = selectedOptions[1].text;
		addParams.value.district = selectedOptions[2].text;
	};

	const onSubmit = async (values) => {
		const identity = getIdentity();
		if (identity == 0) {
			showToast(`请先完成商户审核再${tishi.value}店铺信息`);
		} else if (identity == 1) {
			if (route.params.id == 'add') {
				try {
					const response = await addStore(addParams.value);
					if (response.status == 200) {
						showToast({
							type: 'success',
							message: '添加成功',
							forbidClick: true,
							duration: 1000
						});
						setTimeout(() => {
							window.history.back();
						}, 1000)
					} else {
						showToast({
							type: 'fail',
							message: response.desc,
							forbidClick: true,
							duration: 1000
						});
					}
				} catch (err) {
					showToast({
						type: 'fail',
						message: err.desc,
						forbidClick: true,
						duration: 1000
					});
				}
			} else {
				try {
					const response = await updateStore(updateParams.value);
					if (response.status == 200) {
						showToast({
							type: 'success',
							message: '更新成功',
							forbidClick: true,
							duration: 1000
						});
						setTimeout(() => {
							window.history.back();
						}, 1000)
					} else {
						showToast({
							type: 'fail',
							message: response.desc,
							forbidClick: true,
							duration: 1000
						});
					}
				} catch (err) {
					showToast({
						type: 'fail',
						message: err.desc,
						forbidClick: true,
						duration: 1000
					});
				}
			}
		} else if (identity == 2) {
			showToast(`二级账号无${tishi.value}店铺权限`);
		}
	};

	function goback() {
		window.history.back();
	}
</script>

<style lang="scss" scoped>
	.searchBox {
		background-color: #fff;
		height: 44px;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding: 0 6px;

		.title {
			text-align: center;
			color: #000;
			font-weight: bold;
			box-sizing: border-box;
			height: 44px;
			flex: 0.92;
			line-height: 44px;
		}
	}
</style>
<style>
	/* 可选：适配底部安全区域 */
	.van-popup--bottom {
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>